package org.acooly.secretbox.ui;

import java.text.SimpleDateFormat;
import java.util.LinkedList;
import java.util.List;

import org.acooly.android.utils.ToastUtils;
import org.acooly.secretbox.R;
import org.acooly.secretbox.common.BaseActivity;
import org.acooly.secretbox.service.FileSystem;
import org.acooly.secretbox.service.UserService;
import org.acooly.secretbox.service.domain.FileObject;
import org.acooly.secretbox.service.impl.LocalFileSystem;
import org.acooly.secretbox.service.impl.UserServiceImpl;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class FileManagerActivity extends BaseActivity {

	private static final String TAG = "FileManagerActivity";
	private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	private static final int BUSI_TYPE_LOAD = 1;
	private static final int RESULT_FAIL = 2;

	private UserService userService;
	private FileSystem fileSystem;

	ProgressDialog progressDialog = null;
	List<FileObject> fileObjects = new LinkedList<FileObject>();
	private FileObjectAdapter adapter;
	private ListView listView;

	private String currentPath = "";
	private int chooseType = FileObject.TYPE_FOLDER;

	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			Bundle bundle = msg.getData();
			int type = bundle.getInt("type");
			int result = bundle.getInt("result");
			if (type == BUSI_TYPE_LOAD) {
				if (result == RESULT_OK) {
					progressDialog.dismiss();
					adapter.notifyDataSetChanged();
				} else {
					ToastUtils.showShort(getApplicationContext(), bundle.getString("msg"));
				}
			}
		}

	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.filemanager);
		userService = new UserServiceImpl(this);
		fileSystem = new LocalFileSystem(this);

		adapter = new FileObjectAdapter(this, fileObjects, R.layout.filemanager_list_item);
		listView = (ListView) findViewById(R.id.filemanager_list);
		listView.setAdapter(adapter);

		listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				FileObject object = (FileObject) adapter.getItem(position);
				if (object.getType() != FileObject.TYPE_FILE) {
					doListFile(object.getPath());
				}
			}
		});
		doListFile(currentPath);
		// 导入
		Button select = (Button) findViewById(R.id.filemanager_select);
		select.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
			}
		});

	}

	private void doListFile(final String path) {
		progressDialog = ProgressDialog.show(this, "提示", "正在加载,请等待...", true);
		new Thread() {
			@Override
			public void run() {
				Message message = new Message();
				Bundle bundle = new Bundle();
				bundle.putInt("type", BUSI_TYPE_LOAD);
				int result = RESULT_OK;
				try {
					List<FileObject> objects = fileSystem.list(path);
					fileObjects.clear();
					fileObjects.addAll(objects);
					currentPath = path;
				} catch (Exception e) {
					Log.i(TAG, e.getMessage());
					result = RESULT_FAIL;
					bundle.putString("msg", e.getMessage());
				}
				bundle.putInt("result", result);
				message.setData(bundle);
				handler.sendMessage(message);
			}
		}.start();

	}

	class FileObjectAdapter extends SimpleAdapter {
		private LayoutInflater mInflater;
		private List<FileObject> fileObjects = new LinkedList<FileObject>();
		private int resource;

		public FileObjectAdapter(Context context, List<FileObject> fileObjects, int resource) {
			super(context, null, resource, null, null);
			// fileObjects.add(new FileObject());
			this.fileObjects = fileObjects;
			this.resource = resource;
			this.mInflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {
			return fileObjects.size();
		}

		@Override
		public Object getItem(int position) {
			return fileObjects.get(position);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = mInflater.inflate(resource, null);
				holder.icon = (ImageView) convertView.findViewById(R.id.fileobject_icon);
				holder.name = (TextView) convertView.findViewById(R.id.fileobject_name);
				holder.lastModifyTime = (TextView) convertView.findViewById(R.id.fileobject_lastModifyTime);
				holder.length = (TextView) convertView.findViewById(R.id.fileobject_length);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			// BitmapFactory.decodeResource(getResources(),
			// styleBackgroud[position])

			final FileObject fileObject = fileObjects.get(position);
			holder.name.setText(fileObject.getName());
			if (fileObject.getType() == FileObject.TYPE_FILE) {
				holder.lastModifyTime.setText(sdf.format(fileObject.getLastModifyTime()));
				holder.length.setText(getFileSize(fileObject.getLength()));
				holder.icon.setImageResource(R.drawable.fs_file);
			} else if (fileObject.getType() == FileObject.TYPE_FOLDER) {
				holder.icon.setImageResource(R.drawable.fs_folder);
				holder.length.setText("");
				holder.lastModifyTime.setText("");
			} else {
				holder.icon.setImageResource(R.drawable.fs_back);
				holder.length.setText("");
				holder.lastModifyTime.setText("");
			}
			return convertView;
		}

		private String getFileSize(long length) {
			if (length < 1024) {
				return length + "B";
			}
			if (length < 1024 * 1024) {
				return length / 1024 + "K";
			}
			if (length < 1024 * 1024 * 1024) {
				return length / (1024 * 1024) + "M";
			}
			return length / (1024 * 1024 * 1024) + "G";

		}
	}

	class ViewHolder {
		public ImageView icon;
		public TextView name;
		public TextView lastModifyTime;
		public TextView length;
	}

}